<?php
declare(strict_types=1);

namespace app\controller\admin;

use app\BaseController;
use app\model\{Order, Merchant, User, MerchantFundFlow};
use think\facade\{Db, Cache};
use think\Request;

class DashboardController extends BaseController
{
    /**
     * 获取统计概览
     */
    public function index()
    {
        // 缓存统计数据
        $stats = Cache::remember('dashboard_stats', function() {
            return [
                'merchant_count' => Merchant::where('status', 1)->count(),
                'user_count' => User::count(),
                'order_count' => Order::count(),
                'today_order_count' => Order::whereDay('create_time')->count(),
                'today_order_amount' => Order::whereDay('create_time')->sum('fee_actual'),
                'today_platform_profit' => Order::whereDay('create_time')->sum('platform_profit')
            ];
        }, 300); // 缓存5分钟
        
        return $this->success('获取成功', $stats);
    }
    
    /**
     * 获取订单趋势
     */
    public function orderTrend(Request $request)
    {
        $days = (int)$request->param('days', 7);
        $days = min($days, 30); // 最多30天
        
        $result = [];
        for ($i = $days - 1; $i >= 0; $i--) {
            $date = date('Y-m-d', strtotime("-{$i} days"));
            $result[] = [
                'date' => $date,
                'count' => Order::whereDay('create_time', $date)->count(),
                'amount' => Order::whereDay('create_time', $date)->sum('fee_actual'),
                'profit' => Order::whereDay('create_time', $date)->sum('platform_profit')
            ];
        }
        
        return $this->success('获取成功', $result);
    }
    
    /**
     * 获取商家排行
     */
    public function merchantRank(Request $request)
    {
        $type = $request->param('type', 'order'); // order:订单量 amount:交易额
        $limit = min((int)$request->param('limit', 10), 50);
        
        $startTime = date('Y-m-d 00:00:00', strtotime('-30 days'));
        $endTime = date('Y-m-d 23:59:59');
        
        $query = Order::where('create_time', 'between', [$startTime, $endTime])
            ->group('merchant_id');
            
        if ($type == 'order') {
            $query->field('merchant_id, COUNT(*) as value');
        } else {
            $query->field('merchant_id, SUM(fee_actual) as value');
        }
        
        $list = $query->with(['merchant' => function($query) {
                $query->field('id,merchant_name');
            }])
            ->order('value', 'desc')
            ->limit($limit)
            ->select();
            
        return $this->success('获取成功', $list);
    }
    
    /**
     * 获取资金统计
     */
    public function fundStats(Request $request)
    {
        $startTime = $request->param('start_time', date('Y-m-d 00:00:00', strtotime('-7 days')));
        $endTime = $request->param('end_time', date('Y-m-d 23:59:59'));
        
        // 收入统计
        $incomeStats = MerchantFundFlow::where('create_time', 'between', [$startTime, $endTime])
            ->where('fund_flow_type', 'in', [1,3]) // 充值和订单支付
            ->field('fund_flow_type, SUM(fund_flow_amount) as amount')
            ->group('fund_flow_type')
            ->select();
            
        // 支出统计
        $expenseStats = MerchantFundFlow::where('create_time', 'between', [$startTime, $endTime])
            ->where('fund_flow_type', 'in', [2,4]) // 提现和退款
            ->field('fund_flow_type, SUM(fund_flow_amount) as amount')
            ->group('fund_flow_type')
            ->select();
            
        return $this->success('获取成功', [
            'income' => $incomeStats,
            'expense' => $expenseStats
        ]);
    }
    
    /**
     * 获取实时数据
     */
    public function realtime()
    {
        // 最近1小时数据
        $startTime = date('Y-m-d H:i:s', strtotime('-1 hour'));
        $endTime = date('Y-m-d H:i:s');
        
        $data = [
            // 新增订单
            'new_orders' => Order::where('create_time', 'between', [$startTime, $endTime])
                ->order('id', 'desc')
                ->limit(10)
                ->select(),
                
            // 新增商家
            'new_merchants' => Merchant::where('create_time', 'between', [$startTime, $endTime])
                ->order('id', 'desc')
                ->limit(10)
                ->select(),
                
            // 新增用户
            'new_users' => User::where('create_time', 'between', [$startTime, $endTime])
                ->order('id', 'desc')
                ->limit(10)
                ->select()
        ];
        
        return $this->success('获取成功', $data);
    }
} 